package com.elite.groovy.callback

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

import org.apache.commons.logging.Log

import org.apache.commons.logging.LogFactory

import com.elite.groovy.util.EliteBean
import cn.com.elite.PropertiesUtil
import cn.com.kh.HttpClientProxy
import net.sf.json.JSONArray
import net.sf.json.JSONObject

class ZhenYuyue implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(ZhenYuyue.class);

	@Override
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
		//paramHttpServletResponse.setCharacterEncoding("UTF-8");
		//paramHttpServletResponse.setContentType("application/json;charset=utf-8");
		
		log.debug("开始启动青牛预测外呼真预约名单下发");
		JSONObject result = new JSONObject();
		long startTime=System.currentTimeMillis();
		def count = 0;
		try {
			//获取配置文件中配置好的企业号、代理ip及端口
			PropertiesUtil cfg = new PropertiesUtil();
			def Te_entId = cfg.readValue("QingNiu.EntId");
			String proxyIp = cfg.readValue("QingNiu.ProxyIP");
			int proxyPort=0;
			if(cfg.readValue("QingNiu.ProxyPort")!=null&&cfg.readValue("QingNiu.ProxyPort")!="") {
				proxyPort = cfg.readValue("QingNiu.ProxyPort").toInteger();
			}
			
			/*根据名单状态查询小结为预约(OPEN)状态的、并且是预测式外呼批次、时间范围为预约当天及当天之前的预约名单加入到临时表中、
			 * 临时表推送标记is_push标记为2(预约专用)，推送类型标记为3(预约)，当日第一次执行时候启用，多次执行不重复添加
			 */
			StringBuffer sb = new StringBuffer();
			sb.append("insert into list_push_temporary ");
			sb.append("(id,customer_guid,Listrank,customer_name,mobile,tel_1, ");
			sb.append("atel_1,atel_2,atel_3,atel_4,createddate,createdby, ");
			sb.append("in_enddate,custlist,activity_name,send_type,is_push,objective_guid ) ");
			sb.append("select sys_guid(),c.customer_guid,1,c2.customername,c2.mobile, ");
			sb.append("c2.tel_1,c2.atel_1,c2.atel_2,c2.atel_3,c2.atel_4,sysdate,'SELITE', ");
			sb.append("c.in_enddate,c.stringfield1,b.reservation_activity,'3','2',objective_guid ");
			sb.append("from elitetask e left join customer c on c.customer_guid = e.customer_guid ");
			sb.append("left join customer c2 on c.parent_guid = c2.customer_guid inner join Inflow_rule_configuration l ");
			sb.append("on e.custlistname = l.custlist_name inner join Batch_configuration b ");
			sb.append("on l.activity_name = b.id ");
			sb.append("where c.customertype2_id = '000002' and e.obstatus = 'OPEN' and e.attempt>0 and objectivesubstatus = 'UD0001'  and e.elitetaskstatus= 'APCALL' ");
			sb.append("and e.objectivetype_id in ");
			sb.append("(select map_id category from wo3_frame_map where CATEGORY = 'SALE01') ");
			sb.append("and e.expectstarttime <= (TRUNC(SYSDATE) + 1 - 1 / 86400)  and e.Expectstarttime>=sysdate and e.Expectstarttime<=sysdate+interval '5' minute ");
			sb.append("and c.stringfield16 is null  ");
			sb.append("order by e.elitetaskstatus, c.in_enddate desc ");
			int row1=eliteBean.update(sb.toString(),"dataSource");
			log.debug("当日应推送预约数量(当日+当日之前的预约):"+row1);
			
			
				String selectSQL3="select WEBSERVICEURL from sysc_interface where webtype='QN_MDDR'";
				
				def postURL2=eliteBean.chaxun_sql(selectSQL3, "dataSource");
				log.debug(postURL2);
				def httpURL=postURL2[0].get("WEBSERVICEURL");
				log.debug("青牛地址:"+httpURL);
				JSONObject dataObject2 = null;
				def sendNum=2700; //每批数据分批推送条数
				def con = Math.ceil(row1/sendNum);
				for(int q=1;q<=con;q++) {
					def updateSQL1="update list_push_temporary set Is_push='1' where Is_push='2' and send_type =3 and rownum<='"+sendNum+"'";
					def row4=eliteBean.update(updateSQL1,"dataSource");
					
					//将临时表中标记为预约待下发(is_push标记为2)的名单查询出来转为报文推送给青牛
					String sqls = "select l.customer_guid custId,"+Te_entId+" ENTID,l.activity_name CALLLISTNAME,l.customer_guid recordKey,l.mobile,l.tel_1,l.atel_1,l.atel_2,l.atel_3,l.atel_4,Listrank,s.Agent_Id,s.Staff_Id,l.objective_guid from list_push_temporary l left join elitetask e on l.objective_guid = e.objective_guid left join staff s  on e.Handleby_Id = s.Staff_Id where l.Is_push = '1'and l.send_type = 3 and l.Listrank is not null and e.objective_guid is not null order by in_enddate asc";
					def resultlist2= eliteBean.chaxun_sql(sqls, "dataSource");
					
					JSONArray jsonArray2=JSONArray.fromObject(resultlist2);
					def ListNum2 = jsonArray2.size();
					JSONArray arr = new JSONArray();
					JSONObject obj = new JSONObject();
					JSONObject dataObject= null;;
					
					for(int j=0;j<ListNum2;j++) {
						dataObject=jsonArray2.getJSONObject(j);
						def cust_id=GetJV(dataObject, "CUSTID");
						def entId=GetJV(dataObject, "ENTID");
						def activity_id=GetJV(dataObject, "CALLLISTNAME");
						def recordKey=GetJV(dataObject, "RECORDKEY");
						def objectiveGuid = GetJV(dataObject, "OBJECTIVE_GUID");
						def Listrank = GetJV(dataObject, "LISTTRANK");
						def agentId = GetJV(dataObject, "AGENT_ID");
						def staffId = GetJV(dataObject, "STAFF_ID");
						def phoneNumber1=GetJV(dataObject, "MOBILE");
						def phoneNumber2=GetJV(dataObject, "TEL_1");
						def phoneNumber3=GetJV(dataObject, "ATEL_1");
						def phoneNumber4=GetJV(dataObject, "ATEL_2");
						def phoneNumber5=GetJV(dataObject, "ATEL_3");
						def phoneNumber6=GetJV(dataObject, "ATEL_4");
						if(objectiveGuid==null || objectiveGuid=="") {
							continue;
						}
						JSONObject phoneNumbers = new JSONObject();
						phoneNumbers.put("phoneNumber1", phoneNumber1);
						phoneNumbers.put("phoneNumber2", phoneNumber2);
						phoneNumbers.put("phoneNumber3", phoneNumber3);
						phoneNumbers.put("phoneNumber4", phoneNumber4);
						phoneNumbers.put("phoneNumber5", phoneNumber5);
						phoneNumbers.put("phoneNumber6", phoneNumber6);
						obj.put("custId", cust_id+","+objectiveGuid);
						obj.put("entId", entId);
						obj.put("callListName", activity_id);
						obj.put("recordKey", recordKey);
						obj.put("Listrank", Listrank);
						obj.put("phoneNumbers", phoneNumbers);
						obj.put("exData3",agentId);
						obj.put("exData4",staffId);
						arr.add(obj);
					}
					log.debug("本次推送真预约总条数:"+ListNum2);
					
					//推送数据
					def id=UUID.randomUUID().toString();
					JSONObject objtwo = new JSONObject();
					objtwo.put("batchId", id);
					objtwo.put("total", ListNum2);
					objtwo.put("data", arr);
					
					long time=System.currentTimeMillis();
					def reJson = HttpClientProxy.sendPost(httpURL, objtwo.toString(),proxyIp,proxyPort);
					JSONObject json = new JSONObject().fromObject(reJson);
					//log.debug("真预约名单推送调用返回结果:"+reJson);
					long etime=System.currentTimeMillis();
					//log.debug("接口请求时间："+(etime-time));
					
					String code=json.code;
					StringBuffer sql = new StringBuffer("insert into list_push_history ");
					sql.append("(id,batch_id,customer_guid,is_flag,activity_name,custlist,");
					sql.append("createddate,mobile,tel_1,atel_1,atel_2,atel_3,atel_4,customer_name,send_type,in_enddate,listrank,objective_guid) ");
					sql.append("select sys_guid(),id,customer_guid,'"+code+"',activity_name,custlist,");
					sql.append("sysdate,mobile,tel_1,atel_1,atel_2,atel_3,atel_4,customer_name,send_type,in_enddate,listrank,objective_guid ");
					sql.append("from list_push_temporary where is_push='1' and send_type =3");
					def row7=eliteBean.update(sql.toString(),"dataSource");
					log.debug("本次推送记录至历史表数量:"+row7);
					count+=row7;
					
					
					def deleteSQL1="delete from list_push_temporary where is_push='1' and send_type=3 and Listrank is not null"
					def row6=eliteBean.update(deleteSQL1,"dataSource");
					log.debug("本次推送清除临时表数量:"+row6);

					
				}
					long endTime=System.currentTimeMillis();
					result.put("code", 1);
					result.put("msg", "处理完成、调用处理时长(毫秒):" + (endTime - startTime) + "共推送" + count + "条");
					
					log.debug("青牛预测外呼真预约名单下发结束");	
					//return result.toString();
		}catch(Exception e) {
			result.put("code", 1008);
			result.put("msg", e.getMessage());
		}
	}
	
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null
		try {
			Rev_Value = inJson.getString(getKey)
			//log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey))
				//log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
			} catch (Exception e1) {
				Rev_Value = ""
				//log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				//log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
				Rev_Value = ""
			}
		}
		return Rev_Value
	}
}
